//
//  EditDrugReminderViewController.m
//  安好
//
//  Created by lianchuang on 14-11-28.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "EditDrugReminderViewController.h"

#import "AddDrugReminderCell.h"
#import "AddDrugTimeReminderCell.h"
//点击药品-名称-push到write页面
#import "WriteFamilyViewController.h"
//“剂量”选中器
#import "DrugCountPickerView.h"
//“时间”选择器
#import "MyHourMinutePickerView.h"
//删除这个药品提醒后返回列表页面
#import "TakeDrugReminderViewController.h"
//闹钟提醒
#import "RemindDrugManager.h"

#define EditCellLineColor [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1];

#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

@interface EditDrugReminderViewController ()<UITableViewDataSource,UITableViewDelegate,WriteFamilyViewControllerDelegate>

@property(nonatomic,strong)UITableView * tableView;
//保存时间数组和“添加提醒时间”
@property(nonatomic,strong)NSMutableArray * secondDataArray;
//保存时间数组
@property(nonatomic,strong)NSMutableArray * timeDataArray;
//编辑页面的删除按钮
@property(nonatomic,strong)UIButton * deleteReminderButton;
//编辑页面--删除btn的提醒
@property(nonatomic,strong)UIAlertView * deleteAlertView;
//第一段“药品”“剂量”
@property(nonatomic,strong)AddDrugReminderCell * firstSelectCell;
//第二段“时间”cell
@property(nonatomic,strong)AddDrugTimeReminderCell * secondSelectCell;
//“剂量”选择器
@property(nonatomic,strong)DrugCountPickerView * drugAndDosePickerView;
//“时间”选择器
@property(nonatomic,strong)MyHourMinutePickerView *timeReminderPickerView;
/**
 *  半透明的图片 -- 当点击升起pickerView的时候 这个也sheng起来
 */
@property(nonatomic,strong)UIView * alphaView;

@property(nonatomic,assign)CGFloat cellHeight;

@property(nonatomic,assign)BOOL isFirst;

@end

@implementation EditDrugReminderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isFirst = YES;
    [self makeNavBar];
    
    [self makeTableView];
    [self loadData];
    
    //加载的时候先判断cell多少个，如果下面盖住“删除”按钮，需要把删除按钮线放在最后一个cell的下面，刷新就会到了table的footer上
    CGFloat cellHeight = 44;
    if (IPhone6Plus) {
        cellHeight = 53;
    }
    CGFloat lastCellHight = 20+cellHeight*2+self.timeDataArray.count * cellHeight+cellHeight;
    CGFloat deleteBtnY = kScreenHeight-iOS7TopMargin - cellHeight-30;
    if (deleteBtnY - lastCellHight <= 10) {
        [self createDeleteButtonOnSuperView:self.view  withFram:CGRectMake(15, lastCellHight+10, kScreenWidth-30, cellHeight)];
    }else
    {
        [self createDeleteButtonOnSuperView:self.view  withFram:CGRectMake(15,deleteBtnY , kScreenWidth-30, cellHeight)];
    }
}

#pragma mark - 创建导航条
-(void)makeNavBar
{
    self.navigationItem.title = @"编辑用药提醒";//添加用药提醒
    // 返回按钮图片
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // 完成
    UIBarButtonItem *OkBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(OkButtonclicked)];
    OkBtnImg.tintColor = [UIColor whiteColor];
    OkBtnImg.tag = 100;
    self.navigationItem.rightBarButtonItem = OkBtnImg;
}
//返回展示页面
-(void)backBtnClicked
{
    [self.navigationController popViewControllerAnimated:NO];
}
//“完成”--编辑完之后还是返回到展示页面
//需要更新上传数据，反向传值回到展示页面
-(void)OkButtonclicked
{
    [self AFNetRequestFor_UpData_FamilyDrugReminder];
}
#pragma mark - AFNet-更新家人用药提醒
-(void)AFNetRequestFor_UpData_FamilyDrugReminder
{
    
    if (self.drugName.length == 0) {
        [self showCustomHudSingleLine:@"请添加药品名称"];
        return ;
    }
    if (self.doseCountString.length == 0) {
        [self showCustomHudSingleLine:@"请添加剂量"];
        return ;
    }
    if (self.timeDataArray.count==0 ) {
        [self showCustomHudSingleLine:@"请添加提醒时间"];
        return ;
    }
    NSMutableString * timeString = [NSMutableString stringWithCapacity:0];
    for (int i = 0; i < self.timeDataArray.count; i++) {
        [timeString appendString:self.timeDataArray[i]];
        if (i != self.timeDataArray.count-1) {
            [timeString appendString:@","];
        }
    }

    self.timeString = timeString;
    [self showActionView];
    
    NSString * postURL = [NSString stringWithFormat:@"%@user/drugUpdate/",kBaseURL];
    NSDictionary * parameters = @{@"platform":kPlatform,@"version":kVersion,@"fid":self.familyInfoDic[@"fid"],@"drug":self.drugName,@"dose":self.doseCountString,@"time":self.timeString,@"id":self.familyInfoDic[@"reminderID"]};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        MyNSLog("网络请求成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
        }else
        {
            /**
             *  这个数组保存最终开启的时间数组--传向展示页面
             */
            NSMutableArray * openSitchTimeArray = [NSMutableArray arrayWithCapacity:0];
            
#pragma mark 本地推送闹钟提醒的 key = @"uid,fid,reminderId,time"
            
            //根据传过来的开启时间数组先把所有本地推送闹钟通知删除 --》这步的意思先清空最后再添加
            for (NSString * openTime in self.openTimeReminderArray) {
                NSString * clockTimeKey = [NSString stringWithFormat:@"%@,%@,%@,%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"],openTime];
                [[RemindDrugManager shareInstance] removeRemindWithRemindID:clockTimeKey];
            }
            //如果原来关闭闹钟数组为空，即原来的开关都是开启的
            if (self.closeTimeReminderArray.count == 0)
            {
                //循环把当前的即是最新的时间数组开启闹钟提醒
                for ( NSString * openTime in self.timeDataArray) {
                    NSString * clockTimeKey = [NSString stringWithFormat:@"%@,%@,%@,%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"],openTime];
                    
                    [[RemindDrugManager shareInstance] addNewRemindWithUserName:@"" andMedicineName:@"" andMedicineDosage:@"" andNewTime:openTime andMessage:@"" andUserID:@"2" andRemindID:clockTimeKey andFamilyInfoDic:self.familyInfoDic];
                    //把开启的时间保存
                    [openSitchTimeArray addObject:openTime];
                }
                
            }else{
                
                //筛选
                //如果原来关闭的时间数组不为空，则遍历现在的数组，相同的时间移除，剩余时间就是开启的
                NSPredicate * predicate = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)",self.closeTimeReminderArray];
                NSArray * openArray = [self.timeDataArray filteredArrayUsingPredicate:predicate];
                [openSitchTimeArray setArray:openArray];
                
                /*
                //如果原来关闭的时间数组不为空，则遍历现在的数组，相同的时间移除，剩余时间就是开启的
                for (int i = 0; i < self.timeDataArray.count; i++) {
                    for (int j = 0; j < self.closeTimeReminderArray.count; j++) {
                        if ([self.timeDataArray[i] isEqualToString:self.closeTimeReminderArray[j]]) {
                            //当前的时间数组里有原来关闭的时间，就将当前的时间数组中移除那个关闭的时间
                            [self.timeDataArray removeObject:self.timeDataArray[i]];
                        }
                    }
                }
                //最后-得到的时间就是开启的时间数组
                openSitchTimeArray = self.timeDataArray;
                */
                
                
            }
        
            
            //最终：得到了开启的时间数组，把本地推送闹钟开启
            for (NSString * openTime in openSitchTimeArray)
            {
                //把本地推送闹钟开启
                NSString * clockTimeKey = [NSString stringWithFormat:@"%@,%@,%@,%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"],openTime];
                [[RemindDrugManager shareInstance] addNewRemindWithUserName:@"" andMedicineName:@"" andMedicineDosage:@"" andNewTime:openTime andMessage:@"" andUserID:@"2" andRemindID:clockTimeKey andFamilyInfoDic:self.familyInfoDic];
            }

            //反向传值--代理--把“药品名”，“剂量”，“总的时间字符串”，“开启的时间数组”传给展示页面
            [self.delegate editReminderFinishReloadShowDetialWithDrugName:self.drugName AndDoseCount:self.doseCountString AndTimeString:self.timeString andOpenTimeArray:openSitchTimeArray];
            [self.navigationController popViewControllerAnimated:NO];
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
        MyNSLog("更新用药提醒失败");
         [self hiddenActionView];
    }];
    
}

#pragma mark - 加载数据
-(void)loadData
{

    
    self.secondDataArray = [NSMutableArray arrayWithCapacity:0];
    self.timeDataArray = [NSMutableArray arrayWithCapacity:0];
    NSArray * timeSubArray = [self.timeString componentsSeparatedByString:@","];
    NSArray * sortArr = [timeSubArray  sortedArrayUsingSelector:@selector(compare:)];
    for (NSString * time in sortArr) {
        [self.timeDataArray addObject:time];
    }
    [self.secondDataArray addObject:self.timeDataArray];
    [self.secondDataArray addObject:@"添加提醒时间"];
    
    
}

#pragma mark - tableView--的创建
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    //设置cell之间分割线为None
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
#pragma mark - tableView的代理方法
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (IPhone6Plus) {
        return 53;
    }else{
        return 44;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    CGFloat cellHeight = 44;
    if (IPhone6Plus) {
        cellHeight = 53;
    }
    
 
    if (section == 1) {
         //展示cell的总高度--10的段高，两行cell44*2，10的段高，时间数组行数*44+最后一行44
        CGFloat lastCellHight = 10+cellHeight*2+10+self.timeDataArray.count*cellHeight+cellHeight;
         //整个table的高度kScreenHeight-iOS7TopMargin
         //btn的位置y坐标：按钮离屏幕底部的距离30，按钮行高44。所以坐标是：
        CGFloat deleteBtnY = kScreenHeight-iOS7TopMargin-cellHeight-30;
        
        //小于10 就把在这个删除按钮添加到table的段尾上
        if (deleteBtnY - lastCellHight <=10 ) {
            //删除按钮
            UIView * footerDeleteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10+cellHeight+30)];
            [self createDeleteButtonOnSuperView:footerDeleteView withFram:CGRectMake(15, 10, kScreenWidth-30, cellHeight)];
            return footerDeleteView;
        }
        else
        {
            return nil;
        }
    }else
    {
        return nil;
    }

}
//段尾高度--一共有两段，最后一段达到一定条件就添加删除按钮
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat cellHeight = 44;
    if (IPhone6Plus) {
        cellHeight = 53;
    }
    if (section == 1)//第一段
    {
        //展示cell的总高度--10的段高，两行cell44*2，10的段高，时间数组行数*44+最后一行44
        CGFloat lastCellHight = 10+cellHeight*2+10+self.timeDataArray.count*cellHeight+cellHeight;
        //整个table的高度kScreenHeight-iOS7TopMargin
        //btn的位置y坐标：按钮离屏幕底部的距离30，按钮行高44。所以坐标是：
        CGFloat deleteBtnY = kScreenHeight-iOS7TopMargin-cellHeight-30;
        //cell总高距离btn的顶部相离小于10
        if (deleteBtnY - lastCellHight <= 10)  {
            return 10+cellHeight+30;
        }else
        {
            return 0.01;
        }
    }
    else//之前的短尾高都是0.1
    {
        return 0.01;
    }

}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }else
    {
        return self.timeDataArray.count + 1;
    }
    

}
#pragma mark - ----UITableView的代理方法：Cell-加载
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        AddDrugReminderCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
        if (cell == nil) {
            if (IPhone6Plus) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugReminderCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugReminderCell" owner:self options:nil] firstObject];
            }
        }
        //设置线条
        cell.topLineView.backgroundColor = EditCellLineColor
        cell.bottomLineView.backgroundColor = EditCellLineColor;
        cell.jumpImgView.right = kScreenWidth-15;
        
        if (IPhone6Plus) {
            cell.jumpImgView.right = kScreenWidth - 20;
        }
        cell.itemDetialLable.right = cell.jumpImgView.left-5;
       
        //添加内容
        if (indexPath.row == 0) {
            cell.itemLable.text = @"药品";
            cell.itemDetialLable.text = self.drugName;
            [cell.itemImgView setImage:[UIImage imageNamed:@"药品.png"]];
            cell.topLineView.height = 0.3;
             cell.topLineView.width = kScreenWidth;
            cell.bottomLineView.hidden = YES;
        }else
        {
            [cell.itemImgView setImage:[UIImage imageNamed:@"单位.png"]];
            cell.itemLable.text = @"剂量";
            cell.itemDetialLable.text = self.doseCountString;
            cell.topLineView.frame = CGRectMake(55, 0, kScreenWidth-55, 0.3);
            cell.bottomLineView.frame = CGRectMake(0,cell.height-0.5, kScreenWidth, 0.5);
            if (IPhone6Plus) {
                cell.topLineView.left = 65;
            }
        }
        
        return cell;
        
    }
    else
    {
        AddDrugTimeReminderCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TIME"];
        if (cell == nil) {
            if (IPhone6Plus) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugTimeReminderCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddDrugTimeReminderCell" owner:self options:nil] firstObject];
            }
        }
        //对线条的设置
        cell.topLineView.backgroundColor = EditCellLineColor
        cell.bottomLineView.backgroundColor = EditCellLineColor;
        cell.timeItemImgView.top = (cell.height - cell.timeItemImgView.height)/2.0;
        
        //顶部线条
        if (indexPath.row ==0) {
            cell.topLineView.frame = CGRectMake(0, 0, kScreenWidth, 0.3);
        }else
        {
            cell.topLineView.hidden = YES;
        }
        //底部线条
        if (self.timeDataArray.count == indexPath.row ) {
            cell.bottomLineView.frame = CGRectMake(55, cell.height-0.5, kScreenWidth-55, 0.5);
            if (IPhone6Plus) {
                cell.bottomLineView.left = 65;
            }
        }
        //只有第一行有图片
        if (indexPath.row == 0) {
            [cell.timeItemImgView setImage:[UIImage imageNamed:@"时间.png"]];
        }else
        {
            cell.timeItemImgView.hidden = YES;
        }
        
        
        //先判断时间数组是否已经删除完--全部删除的话那么此时度二段只有1行，
        if (self.timeDataArray.count == 0) {
            cell.getTimeLable.text = @"时间";
            cell.deleteTimeButton.tag = indexPath.row+1000;
            cell.deleteTimeButton.hidden = YES;
            [cell.addTimeImgView setImage:[UIImage imageNamed:@"加号.png"]];
            cell.addTimeImgView.right = kScreenWidth-15;
            cell.bottomLineView.frame = CGRectMake(0,cell.contentView.height-0.5, kScreenWidth,0.5);
            if (IPhone6Plus) {
                cell.addTimeImgView.right = kScreenWidth-22;
                cell.bottomLineView.bottom = 53;
            }
        }
        else//还有时间显示
        {
            MyNSLog("%@,%d", self.timeDataArray,indexPath.row);
            //时间数组不为0，最后一行“添加时间”
            if (indexPath.row ==self.timeDataArray.count)
            {
                cell.addTimeImgView.hidden = NO;
                cell.deleteTimeButton.hidden = YES;
                [cell.addTimeImgView setImage:[UIImage imageNamed:@"加号.png"]];
                cell.addTimeImgView.right = kScreenWidth-15;
                cell.getTimeLable.text = @"添加提醒时间";
                cell.bottomLineView.frame = CGRectMake(0, cell.height-0.5, kScreenWidth, 0.5);
                if (IPhone6Plus) {
                    cell.addTimeImgView.right = kScreenWidth-22;
                    cell.bottomLineView.bottom = 53;
                    
                }
            }
            else
            {
                cell.getTimeLable.text = self.timeDataArray[indexPath.row];
                cell.addTimeImgView.hidden = YES;
                //每一个时间cell---后面的“删除”按钮
                cell.deleteTimeButton.hidden = NO;
                cell.deleteTimeButton.tag = indexPath.row+1000;
                [cell.deleteTimeButton addTarget:self action:@selector(deleteTheCellReminderTime:) forControlEvents:UIControlEventTouchUpInside];
                cell.bottomLineView.frame = CGRectMake(55, cell.height-0.5, kScreenWidth-55, 0.5);
                cell.deleteTimeButton.right = kScreenWidth-15;
                if (IPhone6Plus) {
                    cell.bottomLineView.left = 65;
                    cell.deleteTimeButton.right = kScreenWidth-22;
                    
                }
            }
        }

        return cell;
    }
    
}

#pragma mark --“删除”时间cell---后面的“删除”按钮触发方法
-(void)deleteTheCellReminderTime:(UIButton *)deleteBtn
{
    CGFloat cellHeight = 44;
    if (IPhone6Plus) {
        cellHeight = 53;
    }
    
    
    //开启本地闹钟提醒的key
    NSString * clockTimeKey = [NSString stringWithFormat:@"%@%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"],self.timeDataArray[deleteBtn.tag-1000]];
    
    //无论有没有都给他把这个时间移除---多删除不怕
    [[RemindDrugManager shareInstance] removeRemindWithRemindID:clockTimeKey];

    //把该行cell上的时间从timeDataArray中移除
    [self.timeDataArray removeObjectAtIndex:deleteBtn.tag-1000];
    
    //计算cell的高度--------
    //展示cell的总高度--10的段高，两行cell44*2，10的段高，时间数组行数*44+最后一行44
   
    CGFloat lastCellHight = 10+cellHeight*2+10+self.timeDataArray.count*cellHeight+cellHeight;
    
    //整个table的高度kScreenHeight-iOS7TopMargin
    //btn的位置y坐标：按钮离屏幕底部的距离30，按钮行高44。所以坐标是：
    
    CGFloat deleteBtnY = kScreenHeight-iOS7TopMargin-cellHeight-30;
    
    //如果大于10，说明离开了，把这个删除按钮添加到self.view上
    if (deleteBtnY - lastCellHight >= 10) {
        [self createDeleteButtonOnSuperView:self.view withFram:CGRectMake(15, deleteBtnY, kScreenWidth-30, cellHeight)];
    }
    
    //刷新table
    [self.tableView reloadData];

}

#pragma mark - ---UITableView的代理方法：选中末一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isFirst) {
        [self.drugAndDosePickerView removeFromSuperview];
        [self.timeReminderPickerView removeFromSuperview];
        [self makeDrugAndDosePickerView];
        [self makeTimeReminderView];
        self.isFirst = NO;
    }
    
    //第一段---“药品”“剂量”
    if (indexPath.section == 0) {
        self.firstSelectCell = (AddDrugReminderCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        
        if (indexPath.row == 0)//“药品”push到下一个页面
        {
            WriteFamilyViewController *editDrugName = [[WriteFamilyViewController alloc] init];
            editDrugName.delegate = self;
            editDrugName.navBarTitle = @"请添加药品名称";
            editDrugName.textFieldPlaceholder = @"请添加药品名称";
            editDrugName.textString = self.firstSelectCell.itemDetialLable.text;
            [self.navigationController pushViewController:editDrugName animated:YES];
        }
        if (indexPath.row == 1)//“剂量”
        {
            MyNSLog("选中--“剂量”");
            [self makeAlphaView];
            [self.view bringSubviewToFront:self.drugAndDosePickerView];
            //弹出 剂量pickerView
            [UIView animateWithDuration:0.35 animations:^{
                self.drugAndDosePickerView.frame = CGRectMake(0, kScreenHeight-216-iOS7TopMargin, kScreenWidth, 216);
                self.alphaView.alpha = 0.35;
            }];
        }
    }
    //第二段----时间
    if (indexPath.section == 1) {
        MyNSLog("选中--某一个时间");
        self.secondSelectCell = (AddDrugTimeReminderCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        [self makeAlphaView];
        [self.view bringSubviewToFront:self.timeReminderPickerView];
        //弹出 时间pickerView
        [UIView animateWithDuration:0.35 animations:^{
            self.timeReminderPickerView.frame = CGRectMake(0, kScreenHeight-216-iOS7TopMargin, kScreenWidth, 216);
             self.alphaView.alpha = 0.35;
        }];
    }
    

}
#pragma mark --- 药品名称添加的代理方法
-(void)reloadTableViewSelectedCellPlaceholeder:(NSString *)placeholder
{
    //获取药品名字--添加到itemDetialLable上
    self.firstSelectCell.itemDetialLable.text = placeholder;
    //把编辑好的药品名字重新赋值给drugName
    self.drugName = placeholder;
}
#pragma mark - 药品计量选择器
-(void)makeDrugAndDosePickerView
{
    self.drugAndDosePickerView = [[DrugCountPickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216)];
    [self.view addSubview:self.drugAndDosePickerView];
    
    [self.drugAndDosePickerView.cancleButton addTarget:self action:@selector(drugCancleBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.drugAndDosePickerView.sureButton addTarget:self action:@selector(drugSureBtnClicked) forControlEvents:UIControlEventTouchUpInside];
}
//“取消”按钮
-(void)drugCancleBtnClicked
{
    [self recoverPickerViewDown];
}
//确定 获取剂量
-(void)drugSureBtnClicked
{
    self.firstSelectCell.itemDetialLable.text = self.drugAndDosePickerView.getDrugDose;
    //获取药品剂量
    self.doseCountString = self.drugAndDosePickerView.getDrugDose;
    [self recoverPickerViewDown];
}
#pragma mark - 时间选择器picker
-(void)makeTimeReminderView
{
    self.timeReminderPickerView = [[MyHourMinutePickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216)];
    [self.timeReminderPickerView.cancelButton addTarget:self action:@selector(TimecancelButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.timeReminderPickerView.sureButton addTarget:self action:@selector(TimesureButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.timeReminderPickerView];
    [self.view bringSubviewToFront:self.timeReminderPickerView];
    
}
//"取消"--按钮
-(void)TimecancelButtonClicked
{
    [self recoverPickerViewDown];
}
//确定-选中提醒时间
-(void)TimesureButtonClicked
{
    //选中时间先判断是否和时间数组中的其他时间相同
    for (NSString *time in self.timeDataArray)
    {
        if ([time isEqualToString:[self.timeReminderPickerView getDateString]]) {
            [self showCustomHudSingleLine:@"时间不可重复"];
            return;
        }
    }
    NSIndexPath * indexPath = [self.tableView indexPathForCell:self.secondSelectCell];
    //时间数组为空--选中时间后把他添加进时间数组
    if (self.timeDataArray.count == 0) {
        [self.timeDataArray addObject:[self.timeReminderPickerView getDateString]];
    }
    else//如果不为空
    {
        //判断选中的时最后一行(添加新的时间)
        if (indexPath.row ==self.timeDataArray.count)
        {
            //添加新的时间--存入数组
            [self.timeDataArray addObject:[self.timeReminderPickerView getDateString]];
            
        }
        else//选中的是原来的时间--则是修改原来的时间
        {
            [self.timeDataArray replaceObjectAtIndex:indexPath.row withObject:[self.timeReminderPickerView getDateString]];
        }
        
    }
    //最后对时间排序
    NSArray * sortArr = [self.timeDataArray  sortedArrayUsingSelector:@selector(compare:)];
    [self.timeDataArray removeAllObjects];
    for (NSString * time in sortArr) {
        [self.timeDataArray addObject:time];
    }
    
    [self recoverPickerViewDown];
    //做完之后 刷新页面
    [self.tableView reloadData];
    
}

#pragma mark - --恢复“剂量”“时间”选择器下去
-(void)recoverPickerViewDown
{
    [UIView animateWithDuration:0.35 animations:^{
        self.drugAndDosePickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.timeReminderPickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.alphaView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.alphaView removeFromSuperview];
    }];
}

#pragma mark---编辑“删除”按钮：删除这个药品的提醒
-(void)createDeleteButtonOnSuperView:(UIView *)superView withFram:(CGRect)fram
{
    //先从原来的父视图上移除
    [self.deleteReminderButton removeFromSuperview];
    
    self.deleteReminderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.deleteReminderButton.frame = fram;
    [superView addSubview:self.deleteReminderButton];
    self.deleteReminderButton.backgroundColor = [UIColor colorWithRed:35/255.0 green:205/255.0 blue:235/255.0 alpha:1];
    [self.deleteReminderButton setTitle:@"删除提醒" forState:UIControlStateNormal];
    [self.deleteReminderButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.deleteReminderButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.deleteReminderButton addTarget:self action:@selector(deleteReminderBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    self.deleteAlertView = [[UIAlertView alloc] initWithTitle:@"确定要删除提醒吗" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
}
/**
 *  删除这个药品提醒，并且返回列表页面
 */
-(void)deleteReminderBtnClicked
{
    [self.deleteAlertView show];

}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)//确定
    {
        //确定删除按钮点击后--网络请求删除接口--删除成功pop回到用药列表页面
        [self AFNetRequestFor_Delete_FamilyDrugReminder];
    }
    
}
#pragma mark - AFNet-删除提醒--只有在编辑页面的时候才可以删除该提醒
-(void)AFNetRequestFor_Delete_FamilyDrugReminder
{
    [self showActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@user/drugDelete/",kBaseURL];
    NSString * reminderId = self.familyInfoDic[@"reminderID"];
    NSDictionary * parameters = @{@"platform":kPlatform,@"version":kVersion,@"id":reminderId};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        
        MyNSLog("网络连接成功成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            
            alertContent([responseObject objectForKey:@"msg"]);
            MyNSLog("删除失败");
        }else
        {
            //删除成功就把本地的这个药品ID的所有时间闹钟提醒也删除
            NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
            NSString * timeKey = [NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]];
            [timeUser removeObjectForKey:timeKey];
            [timeUser synchronize];
            
            //把我自己的用药提醒数据也删除了
            NSUserDefaults * MyRrug = [NSUserDefaults standardUserDefaults];
            [MyRrug removeObjectForKey:[NSString stringWithFormat:@"MyDrugReminder%@",self.familyInfoDic[@"uid"]]];

            //顺便也需要把这个药品所有时间的闹钟提醒删除
            //根据传过来的开启时间数组先把所有闹钟通知删除
            for (NSString * openTime in self.openTimeReminderArray) {
                
                NSString * clockTimeKey = [NSString stringWithFormat:@"%@%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"],openTime];
                [[RemindDrugManager shareInstance] removeRemindWithRemindID:clockTimeKey];
            }
            //返回到用药提醒列表页面
            for (NSInteger i = 0; i < self.navigationController.viewControllers.count; i++) {
                if ([self.navigationController.viewControllers[i] isKindOfClass:[TakeDrugReminderViewController class]]) {
                    //回到列表页面
                    [self.navigationController popToViewController:self.navigationController.viewControllers[i] animated:YES];
                }
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("删除用药提醒失败");
        [self hiddenActionView];
    }];
}

#pragma mark - 创建半透明的view
-(void)makeAlphaView
{
    self.alphaView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    self.alphaView.backgroundColor = [UIColor blackColor];
    self.alphaView.alpha = 0;
    [self.view addSubview:self.alphaView];
    //给这个半透明的View添加一个手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alphaViewTapClicked:)];
    [self.alphaView addGestureRecognizer:tap];
}
-(void)alphaViewTapClicked:(UITapGestureRecognizer*)tap{
    
    [self recoverPickerViewDown];
    
}

@end
